package cn.ztr.ymcc.service.impl;

import cn.ztr.ymcc.domain.CourseCollect;
import cn.ztr.ymcc.domain.CourseSummary;
import cn.ztr.ymcc.mapper.CourseCollectMapper;
import cn.ztr.ymcc.mapper.CourseSummaryMapper;
import cn.ztr.ymcc.result.JsonResult;
import cn.ztr.ymcc.service.ICourseCollectService;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

/**
 * <p>
 * 商品收藏 服务实现类
 * </p>
 *
 * @author ztr
 * @since 2023-02-27
 */
@Service
public class CourseCollectServiceImpl extends ServiceImpl<CourseCollectMapper, CourseCollect> implements ICourseCollectService {

    @Autowired
    private CourseSummaryMapper courseSummaryMapper;
    @Override
    @Transactional
    public JsonResult addCollection(Long id, Long userId) {
        //1 查询用户是否已经收藏该课程
        CourseCollect courseCollect = baseMapper.selectOne(new QueryWrapper<CourseCollect>().eq("course_id", id).eq("user_id", userId));
        if (courseCollect!=null) {
            //2 已收藏,取消收藏
            baseMapper.deleteById(courseCollect.getId());
            //3 收藏量-1
            CourseSummary courseSummary = courseSummaryMapper.selectById(id);
            courseSummary.setCollectCount(courseSummary.getCollectCount()-1);
            courseSummaryMapper.updateById(courseSummary);
            return JsonResult.me().setMessage("取消收藏");
        }else{
            //4 未收藏,加入收藏
            CourseCollect addCollection = new CourseCollect().setCourseId(id).setUserId(userId).setCreateTime(System.currentTimeMillis());
            baseMapper.insert(addCollection);
            //5 收藏量+1
            CourseSummary courseSummary = courseSummaryMapper.selectById(id);
            courseSummary.setCollectCount(courseSummary.getCollectCount()+1);
            courseSummaryMapper.updateById(courseSummary);
            return JsonResult.me().setMessage("加入收藏");

        }
    }
}
